﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;

namespace SEP.Admin
{
    public partial class Instruments : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                this.BindInfo();
            }

            ClientScript.RegisterStartupScript(this.GetType(), "InstrumentModalPopup", "function showInstrumentModal() { $find('ShowInstrumentModal').show(); }", true);
        }

        private void BindInfo()
        {
            Common.Utility.BindGridView<Instrument>(grvInstruments, Instrument.GetAll());
            Common.Utility.BindDropDownList<InstrumentType>(ddlInstrumentType, MyCache.GetCodeTableCache<InstrumentType>());
            Common.Utility.BindDropDownList<ManufacturerType>(ddlManufacturerType, MyCache.GetCodeTableCache<ManufacturerType>());
        }

        protected void btnNewInstrument_Click(object sender, EventArgs e)
        {
            pnlNewInstrument.Visible = true;            
            modalNewInstrument.Show();
        }

        protected void btnInstrumentSubmit_Click(object sender, EventArgs e)
        {
            string model = txtModel.Text;

            if (!string.IsNullOrWhiteSpace(model))
            {
                Instrument instrument = new Instrument();
                instrument.Model = model;
                
                InstrumentType it = new InstrumentType();                
                it.ID = new Guid(ddlInstrumentType.SelectedValue);
                it.FillByID();
                instrument.InstrumentType = it;

                ManufacturerType mt = new ManufacturerType();
                mt.ID = new Guid(ddlManufacturerType.SelectedValue);
                mt.FillByID();
                instrument.ManufacturerType = mt;

                if (instrument.Create())
                {
                    txtModel.Text = string.Empty;
                    ddlInstrumentType.SelectedIndex = 0;
                    ddlManufacturerType.SelectedIndex = 0;
                    lblInstrumentError.Visible = false;
                }
                else
                {
                    lblInstrumentError.Visible = true;
                    lblInstrumentError.Text = SEPDefaults.ErrorMessages.GENERIC;
                }

                BindInfo();
            }
        }
    }
}